package com.qf.servlet;

import sun.awt.image.BufImgSurfaceData;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * description:
 * author:zgl
 * QQ: 473584672
 */
@WebServlet(urlPatterns = "/randomCode")
public class randomCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width=80;
        int height=50;
        BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();
        graphics.fillRect(0,0,width,height);
        graphics.setColor(Color.blue);
        String code=creatCode();
        HttpSession session=req.getSession();
        session.setAttribute("code",code);
        session.setAttribute("code_creatTime",System.currentTimeMillis());
        graphics.setColor(Color.RED);
        graphics.setFont(new Font("微软雅黑",Font.BOLD,25));
        graphics.drawString(code,(int)(width*0.15),(int)(height*0.7));
        graphics.setColor(Color.orange);
        for(int i=1;i<=10;i++){
            if(i%3==0){
                graphics.setColor(Color.BLACK);
            }
            graphics.drawLine((int)(Math.random()*width),(int)(Math.random()*height),(int)(Math.random()*width),(int)(Math.random()*height));
        }
        ImageIO.write(image,"jpg",resp.getOutputStream());
    }
    public String creatCode(){
        String code=(int)(Math.random()*9000+1000)+"";
        return code;
    }
}
